from .models import UserProfile

from .ser import UserProfileSer

from rest_framework.views import Response, APIView

from django.contrib.auth import authenticate

import redis

# 使用Redis自带的连接池 完成 Redis高效连接
# 创建一个连接池
pool = redis.ConnectionPool(host="localhost", port="6379", decode_responses=True)
r = redis.Redis(connection_pool=pool)


# Create your views here.


class RegisterView(APIView):
    def post(self, request):
        # 验证图片验证码
        img_code = request.data.get('img_code')

        # 首先 获取uuid 然后去 redis 取之前存储的图片验证码
        img_uuid = request.data.get('uuid')
        img_code_save = r.get(img_uuid)
        if not img_code_save:
            return Response({'msg': '图片验证码失效，请重新获取'})
        elif img_code_save != img_code:
            return Response({'msg': '图片验证码不一致，请重新输入'})

        # 获取短信验证码
        sms_code = request.data.get('sms_code')
        phone = request.data.get('phone')
        # 与redis存储的验证码进行判断
        sms_code_save = r.get(phone)
        if not sms_code_save:
            return Response({'msg': '短信验证码失效，请重新获取'})
        elif sms_code_save != sms_code:
            return Response({'msg': '短信验证码错误，请重新获取'})
        ser = UserProfileSer(data=request.data)
        if ser.is_valid():
            ser.save()
            return Response({'msg': '注册成功', 'code': 200})
        else:
            print(ser.errors)
            return Response({'msg': '注册失败', 'code': 400})


class CheckUniqUserView(APIView):
    def post(self, request):
        # 验证用户名是否唯一
        username = request.data.get('username')
        if UserProfile.objects.filter(username=username):
            return Response({'msg': '用户名已被注册', 'code': '400'})
        return Response({'msg': '用户名可用', 'code': 200})


from .utils import CodeUtil
from captcha.image import ImageCaptcha


class SMSCodeView(APIView):
    def get(self, request):
        # 获取传递来的手机号
        phone = request.GET.get('phone')

        CodeUtil.send_sms_code(phone, r)

        return Response({'msg': '发送成功'})


from io import BytesIO
from django.http.response import HttpResponse


def make_img_code(request):
    # 1.先生存验证
    img_code_str = CodeUtil.make_code_n(4)
    # 保存验证码到redis中

    # 获取传递来的uuid
    uuid_str = request.GET.get('uuid')

    r.set(uuid_str, img_code_str, ex=2 * 60)

    # 2生存一张图片 包含了验证码
    image = ImageCaptcha().generate_image(img_code_str)
    # 3返回
    out = BytesIO()
    image.save(out, 'jpeg')

    return HttpResponse(out.getvalue(), content_type='image/jpeg')


from django.db.models import Q
from django.contrib.auth.hashers import check_password
from django.contrib.auth.backends import ModelBackend


class LoginView(APIView):
    def post(self, request):
        username = request.data.get('username')
        password = request.data.get('password')
        # user=authenticate(request,username=username,password=password)

        user = UserProfile.objects.filter(Q(username=username) | Q(phone=username) | Q(email=username))
        if user and check_password(password, user.password):
            return Response({'msg': '登陆成功'})
        return Response({'msg': '登陆失败'})
